//
//  TakeCodeViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/8/26.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "TakeCodeViewController.h"
#import "TakeListViewController.h"
#import "WaitTakingViewController.h"
#import "EverydayExpressViewController.h"
#import "SocketRequest.h"
#import "Singleton.h"
#import "TakeExpress.h"
#import "TakedExpressCell.h"
#import "ComMethod.h"

@interface TakeCodeViewController ()<SocketRequestDelegate,TakeListViewControllerDelegate> {
    SocketRequest *_socketRequest;
    NSString *_takedTime;
    NSArray *_takedExpressList;
}

@end

@implementation TakeCodeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"客户取件";
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self rightBarButtonItemTitle:@"待取件" Method:@selector(pullWaitTakingVC)];
    _inputView.layer.borderColor = LineColor.CGColor;
    _inputView.layer.borderWidth = 0.5;
    [_codeTextField becomeFirstResponder];
    [_codeTextField addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_codeTextField resignFirstResponder];
}

- (void)pullWaitTakingVC {
    [MobClick event:@"qujian_link_daiqujian"];
    WaitTakingViewController *waitTVC = [[WaitTakingViewController alloc] initWithNibName:@"WaitTakingViewController" bundle:nil];
    [self.navigationController pushViewController:waitTVC animated:YES];
}

- (void)textFieldEditingChanged:(UITextField *)textField {
    if (textField.text.length > 11) {
        textField.text = [textField.text substringToIndex:11];
    }
}

//根据取件码查询快件
- (void)queryExpressSocket {
    [ToastActivity makeActivity:@"快件查询中..." InView:self.view];
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STS5"]];
    if (_codeTextField.text.length == 6) {
        [mutableData appendBytes:[@"00" UTF8String] length:2];
        [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
        [mutableData appendBytes:[SocketMethod checkLegal:_codeTextField.text] length:6];
        [mutableData appendBytes:[@"" UTF8String] length:16];
    } else if (_codeTextField.text.length == 11) {
        [mutableData appendBytes:[@"01" UTF8String] length:2];
        [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
        [mutableData appendBytes:[@"" UTF8String] length:6];
        [mutableData appendBytes:[SocketMethod checkLegal:_codeTextField.text] length:16];
    }
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    [ToastActivity dismissInView:self.view];
    if ([code isEqualToString:SuccessSocket]) {
        NSString *content = [SocketMethod stringDecryHexData:data];
        DLog(@"content:%@",content);
        NSArray *array = [content componentsSeparatedByString:@"|"];
        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:1];
        for (NSString *string in array) {
            if (string.length > 0) {
                TakeExpress *takeExpress = [[TakeExpress alloc] initWithString:string];
                [mutableArray addObject:takeExpress];
            }
        }
        if (mutableArray.count <= 0) {
            [DSToast showText:@"未找到快件，请确认取件码是否正确" InView:self.view];
        } else {
            [MobClick event:@"qujian_btn_chaxun"];
            TakeListViewController *takeLVC = [[TakeListViewController alloc] initWithNibName:@"TakeListViewController" bundle:nil];
            takeLVC.takeExpressList = mutableArray;
            takeLVC.delegate = self;
            if (mutableArray.count == 1) {
                takeLVC.isSingle = YES;
            }
            if (_codeTextField.text.length == 6) {
                takeLVC.sendType = 0;
            } else if (_codeTextField.text.length == 11) {
                takeLVC.sendType = 1;
            }
            [self.navigationController pushViewController:takeLVC animated:YES];
        }
    } else {
        [DSToast showText:msg InView:self.view];
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    [ToastActivity dismissInView:self.view];
    [DSToast showText:msg InView:self.view];
}

#pragma mark TakeListViewControllerDelegate
- (void)successTakeExpresses:(NSArray *)takedExpresses {
    _codeTextField.text = @"";
//    [_codeTextField becomeFirstResponder];
    _takedTime = [ComMethod getTodayYYYYMMDDHHmmss];
    _takedExpressList = takedExpresses;
    [self.tableView reloadData];
}

#pragma mark UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:TelephoneLimit] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    if (![string isEqualToString:filtered]) {
        return NO;
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (_codeTextField.text.length <= 0) {
        [DSToast showText:@"请输入取件码" InView:self.view ShowType:DSToastShowTypeCustom];
        return NO;
    } else if (_codeTextField.text.length != 6 && _codeTextField.text.length != 11) {
        [DSToast showText:@"请输入完整的6位取件码" InView:self.view ShowType:DSToastShowTypeCustom];
        return NO;
    } else if (_codeTextField.text.length == 11 && ![_codeTextField.text hasPrefix:@"1"]) {
        [DSToast showText:@"请输入正确的11位手机号" InView:self.view ShowType:DSToastShowTypeCustom];
        return NO;
    }
    [textField resignFirstResponder];
    [self queryExpressSocket];
    return YES;
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _takedExpressList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (_takedExpressList.count > 0) {
        return 22.0;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 22)];
    headerView.backgroundColor = self.tableView.backgroundColor;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(12, 1, 296, 20)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:11];
    label.textColor = TipTextColor;
    label.text = [NSString stringWithFormat:@"上次已取件:%@",_takedTime];
    [headerView addSubview:label];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"TakedExpressCell";
    TakedExpressCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"TakedExpressCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    TakeExpress *express = [_takedExpressList objectAtIndex:indexPath.row];
    [cell reloadTakedExpressCell:express];
    return cell;
}

#pragma mark NibAction
- (IBAction)queryExpressAction:(id)sender {
    [self.view endEditing:YES];
    if (_codeTextField.text.length <= 0) {
        [DSToast showText:@"请输入取件码" InView:self.view];
    } else if (_codeTextField.text.length != 6 && _codeTextField.text.length != 11) {
        [DSToast showText:@"请输入完整的6位取件码" InView:self.view];
    } else if (_codeTextField.text.length == 11 && ![_codeTextField.text hasPrefix:@"1"]) {
        [DSToast showText:@"请输入正确的11位手机号" InView:self.view ShowType:DSToastShowTypeCustom];
    } else {
        [self queryExpressSocket];
    }
}

- (IBAction)jumpEveryExpressVCAction:(id)sender {
    [MobClick event:@"qujian_link_yiqujian"];
    EverydayExpressViewController *everydayEVC = [[EverydayExpressViewController alloc] initWithNibName:@"EverydayExpressViewController" bundle:nil];
    [self.navigationController pushViewController:everydayEVC animated:YES];
}

- (void)dealloc {
    _socketRequest = nil;
}

@end
